<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/30
 * Time: 9:12
 */

namespace plugin\admin\app\logic\user;


use app\common\lib\Guzzle;
use app\common\lib\GuzzleNew;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\user\UserSpreadKeywordModel;
use support\Cache;
use support\Request;
use support\Response;

class SpreadKeywordLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new UserSpreadKeywordModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        $this->getQiCatKeywordList();
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }

        //$request->inputSet('isdel','0');
        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        foreach($items as &$val){
            $val['work_link_data'] = $val['work_link_data'] ? json_encode(json_decode($val['work_link_data'], true),JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES):'';

        }
        return parent::formatNormal($items, $total);
    }

    protected function getQiCatKeywordList()
    {
        //5分钟之后才能请求一次列表
        $cache = Cache::get('getQiCatKeywordList');
        if($cache){
            return false;
        }
        $param = [
            'product_id'=>1,
            'page'=>1,
            'page_size'=>100,
            'start_date'=>date('Y-m-d',strtotime('-7 day')),
            'end_date'=>date('Y-m-d'),
        ];
        // 准备请求头
        $headers = [
            'X-Qm-Devops-Token'=>config('param.qi_cat_token')
        ];
        $path = 'api/v1/promotion/keyword_page?'.http_build_query($param);
        $result = (new GuzzleNew())->get('https://kol.wtzw.com/',$path,$headers);
        if(!empty($result['code']) && $result['code']==200 && !empty($result['data']['list'])){
            foreach($result['data']['list'] as $val){
                $where = [
                    'user_sn'=>$val['kol_name'],
                    'book_id'=>$val['book_id'],
                    'keyword'=>$val['search_keyword'],
                    ['status','in',[1,2,4]],
                ];
                $this->model->getWhere($where)->update(['status'=>$val['status_text_code'],'reject_reason'=>$val['reject_reason']]);
            }
        }
        Cache::set('getQiCatKeywordList',date('Y-m-d H:i:s'),300);
        return true;
    }

}